package com.tjian.fafa.user.base.chatServices;

import android.util.SparseArray;

import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.commons.GlobalStrings;
import com.tjian.fafa.user.base.mainBody.FriendListPage;
import com.tjian.fafa.user.base.mainBody.MainBodyActivity;
import com.tjian.fafa.user.base.util.UnsavedChatMsg;

import java.util.List;


public class FriendListInfo
{

    public static final String strSplitter = GlobalStrings.friendListDivider;//!!!!!&&&!

    /* single instance */
    private static FriendListInfo mFriendListInfo;

    /* list stores all users */
    private List<UserInfo> mListOfFriends;
    private SparseArray<UserInfo> mSparseArrayOfFriends;   // this is to facilitate the search

    /* retrieve single instance */
    public static FriendListInfo getFriendListInfo()
    {
        if (mFriendListInfo == null)
        {
            mFriendListInfo = new FriendListInfo();
        }
        return mFriendListInfo;
    }

    /* private constructor */
    private FriendListInfo()
    {
        mListOfFriends = InitData.getInitData().getListOfFriends();

        mSparseArrayOfFriends = new SparseArray<UserInfo>();
        for (UserInfo userInfo : mListOfFriends)
        {
            mSparseArrayOfFriends.put(userInfo.getId(), userInfo);
        }
    }

    public void uponMakeNewFriend(UserInfo userInfo)
    {
        int newId = userInfo.getId();
        if (mSparseArrayOfFriends.get(newId) != null)
        {
            return;      // we need to be careful to avoid double insert
        }

        mListOfFriends.add(userInfo);
        mSparseArrayOfFriends.put(userInfo.getId(), userInfo);

        ChatServiceData.getInstance().newUser(userInfo);
        UnsavedChatMsg.getInstance().newUser(userInfo);
        if (MainBodyActivity.getCurPage() == MainBodyActivity.mPageContactsList)
        {
            FriendListPage.getInstance().onFriendListUpdate();
        }
    }

    public void friendGoOnAndOffline(String msg0, int onOff)
    {
        UserInfo uup = new UserInfo(msg0);
        int id = uup.getId();

        UserInfo uux = mSparseArrayOfFriends.get(id);
        uux.setIsOnline(onOff);

        if (MainBodyActivity.getCurPage() == MainBodyActivity.mPageContactsList)
        {
            FriendListPage.getInstance().onFriendListUpdate();
        }
    }

    public UserInfo getUserFromId(int id)
    {

        return mSparseArrayOfFriends.get(id);
    }

    public List<UserInfo> getFriendList()
    {
        return mListOfFriends;
    }

    public String getNameFromId(int id)
    {
        return mSparseArrayOfFriends.get(id).getName();
    }

    public static void closeFriendListInfo()
    {
        mFriendListInfo = null;
    }

    public boolean isIdFriend(int id)
    {
        if (mSparseArrayOfFriends.get(id) != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}
